package models

import (
	"fmt"
	"gin-demo/pkg/setting"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
)

// 定义通用模型结构体
type Model struct {
	ID         int `gorm:"primary_key" json:"id"`
	CreatedOn  int `json:"created_on"`
	ModifiedOn int `json:"modified_on"`
}

// gorm v2版本
// 文档: https://gorm.io/zh_CN/docs/index.html
var db *gorm.DB

func SetUp() {

	var (
		err                                       error
		dbName, user, password, host, tablePrefix string
	)
	// 获取app.ini中数据库相关配置
	dbConfig, err := setting.Cfg.GetSection("database")
	if err != nil {
		log.Fatal(2, "Fail to get section 'database' : %v", err)
	}

	// dbType = dbConfig.Key("TYPE").String()
	dbName = dbConfig.Key("NAME").String()
	user = dbConfig.Key("USER").String()
	password = dbConfig.Key("PASSWORD").String()
	host = dbConfig.Key("HOST").String()
	tablePrefix = dbConfig.Key("TABLE_PREFIX").String()

	// 获取db orm 实例
	// dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, dbName)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   tablePrefix, // 表前缀
			SingularTable: true,        // 如果是true, 表示表杀死单数，比如结构体Tag, 则表为：blog_tag, 如果是false,  则表为：blog_tags
		},
		Logger: logger.Default.LogMode(logger.Info), // 日志的级别
	})
	if err != nil {
		// log.Println(err)
		log.Fatalf("连接mysql失败: %v", err)
	}
}
